
package com.webframe.service.impl;

import java.io.File;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webframe.dao.IJdbcDao;
import com.webframe.service.def.IUserService;
import com.webframe.util.MD5Util;
import com.webframe.util.UUIDGenerator;
@Service
public class UserService implements IUserService
{

	@Autowired
	private IJdbcDao	jdbcDao;

	@Override
	public void addRoleForUser(final String user_id_, final String role_id_)
				throws Exception
	{
		final Map<String, Object> map = new HashMap<String, Object>();
		map.put("USER_ID_", user_id_);
		map.put("ROLE_ID_", role_id_);
		jdbcDao.doInsertExecute("t_user_role", map);
	}

	@Override
	public void delRoleForUser(String user_id_, String role_id_)
				throws Exception
	{
		String sql = "DELETE FROM T_USER_ROLE WHERE USER_ID_='"
					+ user_id_
					+ "' AND ROLE_ID_='"
					+ role_id_
					+ "'";
		jdbcDao.doUpdateBySql(sql);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void addUser(String login_name_, String real_name_, String email_, String password_, String org_id_, String status_)
				throws Exception
	{
		Map<String, Object> map = new HashMap<String, Object>();
		String uuid = UUIDGenerator.getUUID();
		map.put("ID_", uuid);
		map.put("LOGIN_NAME_", login_name_);
		map.put("REAL_NAME_", real_name_);
		map.put("EMAIL_", email_);
		map.put("ENABLED_", true);
		map.put("PASSWORD_", MD5Util.getstrs(password_).toLowerCase());
		map.put("ORG_ID_", org_id_);
		map.put("PreviousPasswordChangeTime",
			new Timestamp(System.currentTimeMillis()));
		map.put("STATUS_", status_);
		jdbcDao.doInsertExecute("t_users", map);
		List result_list = jdbcDao.doQueryBySql("SELECT ID_ FROM t_role where ROLE_='ROLE_USER'");
		Map<String, Object> map_ = new HashMap<String, Object>();
		if (result_list == null || result_list.size() == 0)
		{
			String uuid_init_role_ = UUIDGenerator.getUUID();
			Map<String, Object> t_role_map = new HashMap<String, Object>();
			t_role_map.put("ID_", uuid_init_role_);
			t_role_map.put("ROLE_", "ROLE_USER");
			t_role_map.put("LABEL_", "登录用户");
			jdbcDao.doInsertExecute("t_role", t_role_map);
			map_.put("ROLE_ID_", uuid_init_role_);
		} else
		{
			Map result_map = (Map) result_list.get(0);
			map_.put("ROLE_ID_", result_map.get("ID_"));
		}
		map_.put("USER_ID_", uuid);
		jdbcDao.doInsertExecute("t_user_role", map_);
	}

	@Override
	public void addRole(String role_, String label_) throws Exception
	{
		Map<String, Object> map = new HashMap<String, Object>();
		String id = UUIDGenerator.getUUID();
		map.put("ID_", id);
		map.put("ROLE_", role_);
		map.put("LABEL_", label_);
		jdbcDao.doInsertExecute("t_role", map);
	}

	@Override
	public void updateEnableForUser(String id, boolean enabled) throws Exception
	{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ENABLED_", enabled);
		map.put("ID_", id);
		jdbcDao.doUpdateExecuteByID("t_users", "ID_", id, map);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void updatePwdForUser(String id_, String password_old_, String password_new_)
				throws Exception
	{
		Map user_row_ = jdbcDao.doQueryById(id_, "t_users");
		if (user_row_ == null || user_row_.size() < 1)
		{
			// 传入的id_不对，没查找到对应的用户
			throw new Exception("要修改的用户不存在,请刷新重试!");
		} else
		{
			String pwd_old_ = user_row_.get("PASSWORD_").toString();
			if (!pwd_old_.equalsIgnoreCase(MD5Util.getstrs(password_old_)))
			{
				// 验证原始密码不正确
				throw new Exception("您输入的 <b>当前密码</b> 错误,系统没有做任何修改!");
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("PASSWORD_", MD5Util.getstrs(password_new_).toLowerCase());
		map.put("Constant_PK_", id_);
		jdbcDao.doUpdateExecuteByID("t_users", "ID_", id_, map);
	}

	@Override
	public void updatePwdForUserName(String name_, String password_old_, String password_new_)
				throws Exception
	{
		Map<String, Object> user_row_ = jdbcDao.doQueryBySql(
			"select ID_,LOGIN_NAME_,REAL_NAME_,EMAIL_,ENABLED_,PASSWORD_,PreviousPasswordChangeTime,ORG_ID_ from t_users where LOGIN_NAME_='"
						+ name_
						+ "'")
			.get(0);
		if (user_row_ == null || user_row_.size() < 1)
		{
			// 传入的id_不对，没查找到对应的用户
			throw new Exception("要修改的用户不存在!");
		} else
		{
			String pwd_old_ = user_row_.get("PASSWORD_").toString();
			if (!pwd_old_.equalsIgnoreCase(MD5Util.getstrs(password_old_)))
			{
				// 验证原始密码不正确
				throw new Exception("您输入的 <b>当前密码</b> 错误,系统没有做任何修改!");
			}
		}
		String id_ = user_row_.get("ID_").toString();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("PASSWORD_", MD5Util.getstrs(password_new_).toLowerCase());
		map.put("ID_", id_);
		jdbcDao.doUpdateExecuteByID("t_users", "ID_", id_, map);
	}

	@Override
	public void resetPwd(String id_, String password_new_) throws Exception
	{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("PASSWORD_", MD5Util.getstrs(password_new_).toLowerCase());
		map.put("Constant_PK_", id_);
		jdbcDao.doUpdateExecuteByID("t_users", "ID_", id_, map);
	}

	@SuppressWarnings("rawtypes")
	public List findOrgId(HttpServletRequest request, HttpServletResponse response)
				throws Exception
	{
		String userID = request.getParameter("userId");
		Map map = jdbcDao.doQueryById(userID, "t_users");
		List l = jdbcDao.doQueryBySql("select label_ from t_org where id_ in('"
					+ map.get("ORG_ID_").toString()
					+ "')");
		return l;
	}

	@SuppressWarnings({
				"rawtypes", "unchecked"})
	public void modifyUser(HttpServletRequest request, HttpServletResponse response)
				throws Exception
	{
		String login_name_ = request.getParameter("login_name_");
		String real_name_ = request.getParameter("real_name_");
		String org_id_ = request.getParameter("org_id_");
		String id_ = request.getParameter("user_id_");
		String email_ = request.getParameter("email_");
		Map map = new HashMap();
		map.put("login_name_".toUpperCase(), login_name_);
		map.put("org_id_".toUpperCase(), org_id_);
		map.put("real_name_".toUpperCase(), real_name_);
		map.put("Constant_PK_", id_);
		map.put("email_".toUpperCase(), email_);
		map.put("id_", id_);
		jdbcDao.doUpdateExecuteByID("t_users", "id_", id_, map);
	}

	public void doVirtualDeleteById(String tableName, String ID_)
				throws Exception
	{
		String virtualDeleteSql = "update "
					+ tableName
					+ " set status_ = '0' where ID_ ='"
					+ ID_
					+ "'";
		jdbcDao.doUpdateBySql(virtualDeleteSql);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void doVirtualDeleteAllChildsByPid(String tableName, String pidColumnName, String id)
				throws Exception
	{
		List list = jdbcDao.doQueryBySql("select ID_ from "
					+ tableName
					+ " where "
					+ pidColumnName
					+ " = '"
					+ id
					+ "'");
		if (null != list && list.size() > 0)
		{
			for (int i = 0; i < list.size(); i++)
			{
				Map map = (Map) list.get(i);
				String ID_ = map.get("ID_").toString();
				/**
				 * 如果是组织结构级联删除的话 删除所有子组织结构下的所有用户
				 */
				if ("t_org".equals(tableName))
				{
					doVirtualDelete("update t_users set status_ = 0 where org_id_ = '"
								+ ID_
								+ "'");
				}
				doVirtualDeleteAllChildsByPid(tableName, pidColumnName, ID_);
			}
		}
		doVirtualDelete("update "
					+ tableName
					+ " set status_ = 0 where ID_ = '"
					+ id
					+ "'");
		/**
		 * 组织结构下用户
		 */
		if ("t_org".equals(tableName))
		{
			doVirtualDelete("update t_users set status_ = 0 where org_id_ = '"
						+ id
						+ "'");
		}
	}

	public void doVirtualDelete(String sql) throws Exception
	{
		jdbcDao.doUpdateBySql(sql);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public String getRolesUrl(String username, String path) throws Exception
	{
		String sql = "select r.role_ from t_users u left join t_user_role ur on u.id_ = ur.user_id_ left join t_role r on r.id_ = ur.role_id_ where u.login_name_ = '"
					+ username
					+ "' order by r.role_";
		List li = jdbcDao.doQueryBySql(sql);
		String url = "nobg";
		if (li.size() > 0)
		{
			for (int i = 0; i < li.size(); i++)
			{
				String role_ = ((Map) li.get(i)).get("role_").toString();
				File f = new File(path + role_ + ".gif");
				if (f.exists())
				{
					url = role_;
					break;
				}
			}
		}
		return url;
	}
}
